package com.christian.electronic.invoice.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.christian.electronic.invoice.dao.OrderDetail;
import com.christian.electronic.invoice.dao.OrderMaster;
import com.christian.electronic.invoice.mapper.OrderDetailMapper;
import com.christian.electronic.invoice.mapper.OrderMasterMapper;
import com.christian.electronic.invoice.utils.DateUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Table;
import com.spire.doc.fields.Field;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文件说明：创建电子发票 PDF 文件
 *
 * @Author wang
 * @Date 2019/9/27 13:33
 */
@Slf4j
@Service
public class CreateElectronicInvoiceService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMasterMapper orderMasterMapper;

    /**
     * 生成电子发票文件
     *
     * @return
     */
    public boolean createElectronicInvoice(String orderNumber) {
        log.info("开始生成电子发票pdf文件！");
        try {
            Wrapper<OrderDetail> wrapper = new EntityWrapper<>();
            wrapper.eq("order_number", orderNumber);

            OrderMaster master_condition = new OrderMaster();
            master_condition.setOrderNumber(orderNumber);

            OrderMaster orderMaster = null;
            List<OrderDetail> detailList = null;

            try {
                //查询数据库
                orderMaster = orderMasterMapper.selectOne(master_condition);
                detailList = orderDetailMapper.selectList(wrapper);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询订单详细信息失败：{}", e.getMessage());
            }

            //加载 Word 模板文档
            Document document = new Document();
            document.loadFromFile("src/main/resources/static/ElectronicInvoiceTemplate.docx");

            if (orderMaster != null) {
                //替换文档中以#开头的文本
                document.replace("#customerName", orderMaster.getBuyerName(), true, true);
                document.replace("#contactNum", orderMaster.getBuyerPhone(), true, true);
                document.replace("#shippingAdd", orderMaster.getBuyerAddress(), true, true);
                document.replace("#orderDate", DateUtil.getDateToStr(orderMaster.getCreationTime()), true, true);
                document.replace("#orderNum", orderMaster.getOrderNumber(), true, true);
            }

            String[][] purchaseData = new String[detailList.size()][];

            for (int i = 0; i < purchaseData.length; i++) {
                String[] product = {detailList.get(i).getProductNumber(), detailList.get(i).getProductName(), detailList.get(i).getProductQuantity().toString(), detailList.get(i).getCommodityPrice()};
                purchaseData[i] = product;
            }

            //获取Word模板中的第二个表格
            Table table = document.getSections().get(0).getTables().get(1);
            int rowNum = purchaseData.length - 1;

            //若购买商品多于一项，则添加purhcaseData.Length - 1个行
            if (purchaseData.length > 1) {
                for (int i = 0; i < rowNum; i++) {
                    //将指定个数的第二行的复制行依次添加到第二行下面
                    table.getRows().insert(2 + i, table.getRows().get(1).deepClone());

                    //更新“金额”所对应单元格的公式
                    for (Object object : table.getRows().get(2 + i).getCells().get(4).getParagraphs().get(0).getChildObjects()) {
                        if (object instanceof Field) {
                            Field field = (Field) object;
                            field.setCode(String.format("=C%d*D%d\\# \"0.00\"", 3 + i, 3 + i));
                        }
                        break;
                    }
                }

                //更新“折扣金额”对应的单元格的公式
                for (Object object : table.getRows().get(4 + rowNum).getCells().get(4).getParagraphs().get(0).getChildObjects()) {
                    if (object instanceof Field) {
                        Field field = (Field) object;
                        field.setCode(String.format("=E%d*0.05\\# \"0.00\"", 3 + rowNum));
                    }
                    break;
                }

                //更新“总计”对应的单元格的公式
                for (Object object : table.getRows().get(5 + rowNum).getCells().get(4).getParagraphs().get(0).getChildObjects()) {
                    if (object instanceof Field) {
                        Field field = (Field) object;
                        field.setCode(String.format("=E%d-E%d\\# \"￥#,##0.00\"", 3 + rowNum, 5 + rowNum));
                    }
                    break;
                }
            }

            log.info("开始写入数据！");
            for (int r = 0; r < purchaseData.length; r++) {
                for (int c = 0; c < purchaseData[r].length; c++) {
                    //将数据从表格的第二行开始写入表格
                    table.getRows().get(r + 1).getCells().get(c).getParagraphs().get(0).setText(purchaseData[r][c]);
                }
            }
            log.info("写入数据完成！");

            //保存为PDF格式文档
            document.saveToFile("src/main/resources/static/" + orderNumber + ".pdf", FileFormat.PDF);
            log.info("生成电子发票 PDF 文件！");

            return true;
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }
    }
}
